package com.buobao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.buobao.entity.Member;
import com.buobao.mapper.MemberMapper;
import com.buobao.service.MemberService;
import com.buobao.service.exception.BussinessException;
import com.buobao.utils.MD5Utils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

@Service("memberService")
public class MemberServiceImpl implements MemberService {
    @Resource
    private MemberMapper memberMapper;

    @Transactional
    @Override
    public Member insertMember(Member member) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",member.getUsername());
        queryWrapper.eq("nickname",member.getNickName());
        List<Member> members = memberMapper.selectList(queryWrapper);
        if (members!=null && members.size()>0) {
            throw new BussinessException("M01","用户名已存在");
        }
        int salt = new Random().nextInt(100000);
        member.setSalt(salt);
        member.setPassword(MD5Utils.md5Digest(member.getPassword(),salt));
        memberMapper.insertMember(member);
        return member;
    }

    @Override
    public Member selectMemberByUsernameAndPassword(String username, String password) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Member member = memberMapper.selectOne(queryWrapper);
        if (member== null) {
            throw new BussinessException("M02","用户名不存在");
        }
        password = MD5Utils.md5Digest(password,member.getSalt());
        if (!password.equals(member.getPassword())) {
            throw new BussinessException("M03","密码错误");
        }
        return member;
    }
}
